#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : BaseEditor(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    setWindowTitle(SP_NAME);
    ui->kw->installEventFilter(this);   //为lineEdit安装过滤器
    loadConfig();
    model=new QSqlTableModel(this);
    ui->tableView->setModel(model);
}

void Widget::showConfigException()
{
    int btn=QMessageBox::warning(this,"异常情况",
                                 "配置文件缺少必要信息，程序现在退出！",
                                 QMessageBox::Yes, QMessageBox::Yes);
    if(btn == 0x00004000)
        qApp->quit();
}

void Widget::loadConfig()
{
    Pie pie;
    if(pie.load(M_INFO))
    {
        table=pie.value("table").toString();
        auto cols=pie.value("columns").toArray();
        foreach (auto col, cols) {
            columns.append(col.toString());
        }
        columnIndex=pie.value("index").toInt(-1);
        if(columns.isEmpty() || columnIndex == -1)
            showConfigException();
        else {
            column=columns.at(columnIndex);
        }

        if(pie.contain("hideColumns"))
        {
            auto cols=pie.value("hideColumns").toArray();
            foreach (auto col, cols) {
                int index=col.toInt(0);
                hideColumns.insert(index);
            }
        }
    }
    else
        showConfigException();
}

bool Widget::eventFilter(QObject *target, QEvent *event)
{
    if(target == ui->kw && event->type() == QEvent::FocusIn)
    {
        QString kw=qApp->clipboard()->text();
        if(!kw.isEmpty())
        {
            ui->kw->setText(kw);
            query(kw);
            return true;
        }
    }
    return QWidget::eventFilter(target,event);     // 最后将事件交给父窗口
}

Widget::~Widget()
{
    delete ui;
}

void Widget::query(const QString &kw)
{
    model->setTable(table);
    model->setFilter(QString("%1 like '%%2%'").arg(column).arg(kw));
    model->select();

    if(!hideColumns.isEmpty())
        foreach (int index, hideColumns) {
            ui->tableView->hideColumn(index);
        }

    ui->tableView->resizeColumnToContents(columnIndex);
}

void Widget::on_btn_paste_clicked()
{
    QString kw=qApp->clipboard()->text();
    if(kw.isEmpty())
        return;

    query(kw);
}

void Widget::on_kw_returnPressed()
{
    QString kw=ui->kw->text().trimmed();
    if(!kw.isEmpty())
        query(kw);
}
